package com.aiwei.tdjk.controller;

import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.dto.request.CustomsHandbookPagerRequest;
import com.aiwei.tdjk.entity.CustomsHandbook;
import com.aiwei.tdjk.enums.CustomsHandbookStatusEnum;
import com.aiwei.tdjk.service.CustomsHandbookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
@RequestMapping(value = "/admin/customsHandbook")
public class CustomsHandbookController extends BaseController {

	@Autowired
	private CustomsHandbookService customsHandbookService;

	protected void setCommonData(Model model) {
		model.addAttribute("statusList", CustomsHandbookStatusEnum.values());
	}


	@RequestMapping(value = {"/list"}, method = RequestMethod.GET)
	public String list(CustomsHandbookPagerRequest request, Model model) {
		setCommonData(model);
		model.addAttribute("page", customsHandbookService.find(request));
		model.addAttribute("customsHandbook", request);
		return viewName("list");
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String showCreateForm(Model model) {

		setCommonData(model);
		model.addAttribute(Constants.OP_NAME, "新增");
		if (!model.containsAttribute("m")) {
			CustomsHandbook customsHandbook = new CustomsHandbook();
			model.addAttribute("m", customsHandbook);
		}
		return viewName("editForm");
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(
			Model model, @Valid @ModelAttribute("m") CustomsHandbook m, BindingResult result,
			RedirectAttributes redirectAttributes) {
		if (hasError(result)) {
			return showCreateForm(model);
		}
		customsHandbookService.add(m);
		redirectAttributes.addFlashAttribute(Constants.MESSAGE, "新增成功");
		return redirectToUrl("list");
	}

	@RequestMapping(value = "{id}/update", method = RequestMethod.GET)
	public String showUpdateForm(@PathVariable("id") Long id, Model model) {
		setCommonData(model);
		model.addAttribute(Constants.OP_NAME, "修改");
		model.addAttribute("m", customsHandbookService.get(id));
		return viewName("editForm");
	}

	@RequestMapping(value = "{id}/update", method = RequestMethod.POST)
	public String update(
			Model model, @Valid @ModelAttribute("m") CustomsHandbook m, BindingResult result,
			RedirectAttributes redirectAttributes) {
		if (hasError(result)) {
			return showUpdateForm(m.getId(), model);
		}
		customsHandbookService.update(m);
		redirectAttributes.addFlashAttribute(Constants.MESSAGE, "修改成功");
		return redirectToUrl("list");
	}

}
